#ifndef ACAPELLA_SYNCHRONIZE_SEMAPHORE_LINUX_H
#define ACAPELLA_SYNCHRONIZE_SEMAPHORE_LINUX_H

#include <semaphore.h>

namespace acapella
{
namespace synchronize
{

class semaphore
{
public:
	semaphore(_uint32_ initCount = 0)
	{
		sem_init(&sem_, false, initCount);
	}

	~semaphore()
	{
		sem_destroy(&sem_);
	}

	int post()
	{
		return sem_post(&sem_);	
	}

	int wait()
	{
		return sem_wait(&sem_);
	}

	int timedwait(_uint32_ timeout)
	{
		timespec tsp;
		maketimeout(&tsp, timeout);

		return sem_timedwait(&sem_, &tsp); 
	}

	void maketimeout(struct timespec *tsp, _uint32_ msTimeout)
	{
		struct timeval now;
		gettimeofday(&now, NULL); 

		tsp->tv_sec = now.tv_usec + (msTimeout / 1000);
		tsp->tv_nsec = now.tv_usec * 1000 + ((msTimeout % 1000) * 1000);

		return;
	}

private:
	sem_t sem_;

	semaphore(const semaphore&);
	semaphore& operator=(const semaphore&);
};


}
}


#endif
